package com.tanhua.dubbo.api;

import com.tanhua.dubbo.api.mongo.BaiduApi;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.awt.*;


@DubboService
public class BaiduApiImpl implements BaiduApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     *      上报位置信息
     * @param userId
     * @param x
     * @param y
     * @param addrStr
     */
    @Override
    public void sendLocation(Long userId, Double x, Double y, String addrStr) {
        long timeMillis = System.currentTimeMillis();
        Query query = new Query(Criteria.where("userId").is(userId));
        GeoJsonPoint location = new GeoJsonPoint(x,y);
        if (mongoTemplate.exists(query, UserLocation.class)) {
            Update update = new Update();
            update.set("updated",timeMillis);
            update.set("location",location);
            update.set("address",addrStr);
            mongoTemplate.updateFirst(query, update,UserLocation.class);

        }else {
            UserLocation userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setLocation(location);
            userLocation.setAddress(addrStr);
            userLocation.setCreated(timeMillis);
            userLocation.setUpdated(timeMillis);
            mongoTemplate.insert(userLocation);
        }

    }
}
